/**
 * 权限校验mixin
 */

import EventEmitter from '@/utils/event'

export default {
  directives: {
    auth(el, binding) {
      let _fn = authMap => {
        let value = binding.value
        let valid = false
        if (typeof value === 'string') {
          valid = !!authMap.find(e => e === value)
        } else {
          valid = !!value
        }
        if (!valid) {
          el.style.display = 'none'
        }
      }
      let authMap = window._authMap
      if (!authMap) {
        EventEmitter.$once('get_auth_map', _fn)
      } else {
        _fn(authMap)
      }
    }
  },
  methods: {
    checkAuth(auth) {
      let _authMap = window._authMap
      return new Promise((res, rej) => {
        let _fn = authMap => {
          res(!!authMap.find(e => e === auth))
        }
        if (!_authMap) {
          EventEmitter.$once('get_auth_map', _fn)
        } else {
          _fn(_authMap)
        }
      })
    }
  }
}
